package com.tm.util;

import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class StringUtilsEx {
	
	/**
	 * 判断字符串是否为数字
	 * @param str 需要验证的字符串-String
	 * @return boolean
	 */
	public static boolean IsNum(String str){
		if(str!=null){
			int n=str.length();
			for(int i=0;i<n;i++){
				if(!java.lang.Character.isDigit(str.charAt(i))){
					return false;
				}
			}
		}
		else{
			return false;
		}
		return true;
	}

	/** 
     * 验证一个字符串是否是Float类型 
     *   
     * @param s 要验证的字符串 
     * @return 如果是Float类型则返回true,否则返回false 
     */ 
    public static boolean IsFloat(String s) {   
        if (s == null || s.equals(""))   
            return false;   
        String num = "0123456789.";   
        if (s.indexOf('.') >= 0)   
            if (s.indexOf('.', s.indexOf('.') + 1) > 0)   
                return false;   
        for (int i = 0; i < s.length(); i++) {   
            if (num.indexOf(s.charAt(i)) < 0) {   
                return false;   
            } else {   
                try {   
                    Float.parseFloat(s);   
                } catch (NumberFormatException e) {   
                    return false;   
                }   
            }   
        }   
        return true;   
    }   
	
	/**
	 * 检查字符串中sql关键字
	 * @param str
	 * @return
	 */
	public static boolean CheckSqlString(String str){
	    String sql_str = "exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare";
	    String[] str1=sql_str.split("|");
	    for (int i=0 ; i < str1.length ; i++ ){
	        if (str.toLowerCase().indexOf(str1[i])>=0){
	            return false;
	        }
	    }
	    return true;
	 }
	
	/**
	 * 16进制字符串转换成字节数组
	 * @param hex
	 * @return
	 */
	public static byte[] hex2Byte(String hex) {
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}
	
	/**
	 * base64解密
	 * @param instr
	 * @return
	 */
	public static final byte[] base642byte(String instr) {
		try {
			return new BASE64Decoder().decodeBuffer(instr);
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}

	/**
	 * base64加密
	 * @param instr
	 * @return
	 */
	public static final String byte2base64(byte[] bytes) {
		try {
			return new BASE64Encoder().encode(bytes);
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}
	
	/** 
     * 编码 
     * @param cookieStr 
     * @return 
     */  
    public static String encodeBase64(String cookieStr){  
          
        try {  
            cookieStr = new String(Base64.encodeBase64(cookieStr.getBytes("UTF-8")));  
        } catch (UnsupportedEncodingException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return cookieStr;  
    }  
  
    /** 
     * 解码 
     * @param cookieStr 
     * @return 
     */  
    public static String decodeBase64(String cookieStr){  
        try {  
            cookieStr = new String(Base64.decodeBase64(cookieStr.getBytes()), "UTF-8");  
        } catch (UnsupportedEncodingException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return cookieStr;  
    }  
	
	/**
	 * 过滤特殊字符,防止SQL注入
	 */
	public static String filterXML(String inStr) {
		String filtered = inStr;
		if (filtered != null) {
			filtered = filtered.replaceAll("'", "\"").replaceAll("<", "&lt;").replace(">", "&gt;");
		}
		return filtered;
	}
	
	/**
	 * 过滤特殊字符,防止SQL注入
	 */
	public static String filterSQL(String inStr) {
		String filtered = inStr;
		if (filtered != null) {
			filtered = filtered.replaceAll("'", "\"");
		}
		return filtered;
	}

	/**
	 * 字节数组转换成16进制字符串
	 * @param bArray
	 * @return
	 */
	public static final String bytes2Hex(byte[] bArray) {
		StringBuffer sb = new StringBuffer(bArray.length);
		String sTemp;
		for (int i = 0; i < bArray.length; i++) {
			sTemp = Integer.toHexString(0xFF & bArray[i]);
			if (sTemp.length() < 2)
				sb.append(0);
			sb.append(sTemp.toUpperCase());
		}
		return sb.toString();
	}

	private static byte toByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}
	
	/**
	 * 判断字符串是否有效长度是否在许可范围内
	 * @param min 最小长度-int
	 * @param max 最大长度-int
	 * @param str 需要验证的字符串-String
	 * @return boolean
	 */
	public static boolean StringLenCheck(int min,int max,String str){
		boolean flag=false;
		if(str!=null){
			int n=str.length();
			if(n>=min&&n<=max){
				return true;
			}
		}
		return flag;
	}

	/**
	 * 屏蔽字符串(字符中间一半为*)
	 * @param str
	 * @return
	 */
	public static String StringShield(String str){
		String shield="";
		if(str.length()==1){
			return "*";
		}
		else if(str.length()==2){
			return str.substring(0,1)+"*";
		}
		int n=(int)(str.length()/2);
		int n1=(int)((str.length()-n)/2);
		for(int i=1;i<=n;i++){
			shield=shield+"*";
		}
		shield=str.substring(0,n1)+shield+str.substring(n+n1);
		return shield;
	}
	
	/**
	 * 获取定长随机字符串
	 * @param length
	 * @return
	 */
	public static String RandomString(int length){
		Random randGen= new Random();
		char[] numbersAndLetters=("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
		char[] randBuffer = new char[length];
		for (int i=0; i<randBuffer.length; i++){      
			randBuffer[i] = numbersAndLetters[randGen.nextInt(62)];        
		}
		return new String(randBuffer);
	}
	
	/**
	 * 获取定长随机数字字符串
	 * @param length
	 * @return
	 */
	public static String RandomNumString(int length){
		Random randGen= new Random();
		char[] numbersAndLetters=("0123456789").toCharArray();
		char[] randBuffer = new char[length];
		for (int i=0; i<randBuffer.length; i++){      
			randBuffer[i] = numbersAndLetters[randGen.nextInt(10)];        
		}
		return new String(randBuffer);
	}
	
	/**
	 * 验证邮箱的有效性
	 * @param email 邮箱-String
	 * @return boolean
	 */
	public static boolean IsEmail(String email){
		boolean flag=false;
		if(StringLenCheck(5,30,email)){
			//不能有连续的.
			if(email.indexOf("..") == -1){
				//必须带有@
				int atCharacter = email.indexOf("@");
				if (atCharacter > 0){
					//最后一个.必须在@之后,且不能连续出现
					if(atCharacter+1 < email.lastIndexOf('.')){
						//不能以.结束和开始
						if (email.indexOf(".")>0 && email.lastIndexOf(".")<email.length()-1){
							//不能以@结束和开始
							if (email.indexOf("@")>0 && email.lastIndexOf("@")<email.length()-1){
								return true;
							}
						}
					}
				}
			}
		} 
		return flag;  
	}
	

	/**
	 * 验证是否是手机号码格式有效性
	 * @param str
	 * @return
	 */
	public static boolean IsMobilePhone(String str){
		boolean flag=false;
		if(StringLenCheck(11,11,str)){
			if(IsNum(str)){
				if(str.startsWith("13")){
					flag=true;
				}
				else if(str.startsWith("15")){
					flag=true;
				}
				else if(str.startsWith("18")){
					flag=true;
				}
			}
		}	
		return flag;
	}
	
	
	/**
	 * 验证Qq格式有效性
	 * @param str
	 * @return
	 */
	public static boolean IsQq(String str){
		boolean flag=false;
		if(str.length()==0){
			return true;
		}
		if(StringLenCheck(5,11,str)){
			if(IsNum(str)){
				flag=true;
			}
		}	
		return flag;
	}
	
	/**
	 * 验证日期格式有效性
	 * @param str
	 * @return
	 */
	public static boolean IsDate(String str){
		boolean flag=false;
		if(str.length()==0){
			return true;
		}
		if(!StringLenCheck(10,10,str)){
			return flag;
		}
		String s= "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";   
        Pattern p = Pattern.compile(s);    
        Matcher m = p.matcher(str);    
        flag = m.matches();    
		return flag;
	}
	
	/**
	 * 15位身份证验证
	 * @param str
	 * @return
	 */
	public static boolean IsIdCard15(String str){
		boolean flag=false;
		if(!StringLenCheck(15,15,str)){
			return false;
		}
		String date="";
		date="19"+str.substring(6,8);
		date=date+"-"+str.substring(8,10);
		date=date+"-"+str.substring(10,12);
		if(IsDate(date)){
			flag=true;
		}
		return flag;
	}

	/**
	 * 18位身份验证
	 * @param str
	 * @return
	 */
	public static boolean IsIdCard18(String str){
		boolean flag=false;
		if(!StringLenCheck(18,18,str)){
				return false;
		}
		final int[] Verify = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
		final int[] lastVerify = { 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 };
		int[] ai=new int[18];
		String date="";
		String cardStr="";
		//验证日期
		date=str.substring(6,10);
		date=date+"-"+str.substring(10,12);
		date=date+"-"+str.substring(12,14);
		cardStr=str.substring(0,17);
		if(!IsDate(date)){
			return false;
		}
		//验证最后一位码
		int sum = 0;
		for (int i = 0; i < 17; i++) {
			String k = cardStr.substring(i, i + 1);
			ai[i] = Integer.parseInt(k);
		}
		for (int i = 0; i < 17; i++) {
			sum = sum + Verify[i] * ai[i];
		}
		String verifyStr=str.substring(17,18);
		int verifyNum=sum % 11;
		String lastStr="";
		if(verifyNum==2){
			lastStr="X";
		}
		else{
			lastStr=String.valueOf(lastVerify[verifyNum]);
		}
		if(verifyStr.equals(lastStr)){
			flag=true;
		}
		return flag;
	}

	/**
	 * 统一验证身份证
	 * @param str
	 * @return
	 */
	public static boolean IsIdCard(String str){
		if(StringLenCheck(15,15,str)){
			return IsIdCard15(str);
		}
		if(StringLenCheck(18,18,str)){
			return IsIdCard18(str);
		}
		return false;
	}
	
	/**
	 * 验证IP地址
	 * @param str
	 * @return
	 */
	public static boolean IsIp(String str){
		String[] s=str.split(".");
		if(s.length==4){
			for(int i=0;i<s.length;i++){
				if(!IsNum(s[i])){
					return false;
				}
				int num=Integer.parseInt(s[i]);
				if(num<0){
					return false;
				}
				if(num>=255){
					return false;
				}
				if(i==0||i==3){
					if(num==0){
						return false;
					}
				}
			}
		}
		else{
			return false;
		}
        return true;
	}
	
	/**
	 * 验证字符串是否是邮编
	 * @param str
	 * @return
	 */
	public static boolean IsPostCode(String str){
		boolean flag=false;
		if(str.length()==0){
			return true;
		}
		if(StringLenCheck(6,7,str)){
			if(IsNum(str)){
				flag=true;
			}
		}	
		return flag;
	}
	
	/**
	 * 特殊字符处理escape编码
	 * @param str
	 * @return
	 */
	 public static String  escape (String src)
	 {
	  int i;
	  char j;
	  StringBuffer tmp = new StringBuffer();
	  tmp.ensureCapacity(src.length()*6);

	  for (i=0;i<src.length() ;i++ )
	  {

	   j = src.charAt(i);

	   if (Character.isDigit(j) || Character.isLowerCase(j) || Character.isUpperCase(j))
	    tmp.append(j);
	   else
	    if (j<256)
	    {
	    tmp.append( "%" );
	    if (j<16)
	     tmp.append( "0" );
	    tmp.append( Integer.toString(j,16) );
	    }
	    else
	    {
	    tmp.append( "%u" );
	    tmp.append( Integer.toString(j,16) );
	    }
	  }
	  return tmp.toString();
	 }

	 /**
		 * 特殊字符处理unescape解码
		 * @param str
		 * @return
		 */
	 public static String  unescape (String src)
	 {
	  StringBuffer tmp = new StringBuffer();
	  tmp.ensureCapacity(src.length());
	  int  lastPos=0,pos=0;
	  char ch;
	  while (lastPos<src.length())
	  {
	   pos = src.indexOf("%",lastPos);
	   if (pos == lastPos)
	    {
	    if (src.charAt(pos+1)=='u')
	     {
	     ch = (char)Integer.parseInt(src.substring(pos+2,pos+6),16);
	     tmp.append(ch);
	     lastPos = pos+6;
	     }
	    else
	     {
	     ch = (char)Integer.parseInt(src.substring(pos+1,pos+3),16);
	     tmp.append(ch);
	     lastPos = pos+3;
	     }
	    }
	   else
	    {
	    if (pos == -1)
	     {
	     tmp.append(src.substring(lastPos));
	     lastPos=src.length();
	     }
	    else
	     {
	     tmp.append(src.substring(lastPos,pos));
	     lastPos=pos;
	     }
	    }
	  }
	  return tmp.toString();
	 }
	 
	 /**
	 * 得到UUID
	 * @return
	 */
	public static String getUUID() {
		  String str = UUID.randomUUID().toString();
		  String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
		 return temp;
	}

	 /*public static void main(String[] args) 
	 {
	  System.out.println(StringUtilsEx.get16UUID());
	 }*/
	 
	 public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",  
         "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",  
         "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",  
         "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",  
         "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",  
         "W", "X", "Y", "Z" };  

	public static String get16UUID() {
		 StringBuffer shortBuffer = new StringBuffer();  
		 String uuid = UUID.randomUUID().toString().replace("-", "");  
		 for (int i = 0; i < 16; i++) {  
		     String str = uuid.substring(i * 2, i * 2 + 2);  
		     int x = Integer.parseInt(str, 36);  
		     shortBuffer.append(chars[x % 0x3E]);  
		 }  
		 return shortBuffer.toString();  
	}  
}
